package com.itheima.putige.putige.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.putige.putige.common.R;
import com.itheima.putige.putige.entity.User;
import com.itheima.putige.putige.service.UserService;
import com.itheima.putige.putige.utils.RandomName;
import com.itheima.putige.putige.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author XGC
 * @description: TODO
 * @date 2022/03/01 19:36
 * @title: UserController
 * @projectName ruiji
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @Author XGC
     * @Description //TODO 生成验证码
     * @Date 19:25 2022/03/01
     * @Param [session, user]
     * @return com.itheima.putige.putige.common.R<java.lang.String>
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session,@RequestBody User user){
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为：{}",code );
            //将生成的验证码保存在session中
            //session.setAttribute(phone,code);

            //需要将生成的验证码保存到Redis,设置过期时间5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("验证码按发送成功");
        }
        return R.error("验证码发送失败");
    }

    /**
     * @Author XGC
     * @Description //TODO 登录
     * @Date 19:40 2022/03/01
     * @Param [map, session]
     * @return com.itheima.putige.putige.common.R<com.itheima.putige.putige.entity.User>
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //根据手机号查找用户
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,phone);
        User user = userService.getOne(lqw);
        //获取后端生成的验证码
        //Object attributeCode = session.getAttribute(phone);

        //从Redis中获取缓存的验证码
        Object attributeCode = redisTemplate.opsForValue().get(phone);

        if(attributeCode != null && code.equals(attributeCode)){
            //判断用户是否已存在，不存在则自动添加
            if(user == null){
                user = new User();
                //生成随机名
                user.setName(RandomName.getStringRandom(8));
                user.setPhone(phone);
                user.setStatus(1);

                userService.save(user);
            }
            //将用户ID存入session中
            session.setAttribute("user",user.getId());

            //从Redis中删除缓存的验证码
            redisTemplate.delete(phone);

            return R.success(user);
        }
        return R.error("验证码错误！");
    }

    /**
     * @Author XGC
     * @Description //TODO 退出登录
     * @Date 20:02 2022/03/01
     * @Param [session]
     * @return com.itheima.putige.putige.common.R<java.lang.String>
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("已退出登录！");
    }


}
